package com.reider.log4AS3.utils
{	
	import flash.utils.Proxy;
	import flash.utils.flash_proxy;
	import flash.events.IEventDispatcher;
	import flash.events.Event;
	
	/**
	 * @private
	 */
	
	public dynamic class BufferedCaller extends Proxy
	{
		
		private var eventFired:Boolean
		private var dispatcher:IEventDispatcher
		private var eventType:String
		private var target:*
		private var buffer:Array
	
	    public function BufferedCaller(target:*, dispatcher:IEventDispatcher, eventType:String)
	    {
			this.target = target
			this.dispatcher = dispatcher
			this.eventType = eventType
			this.eventFired = false
				
	    	buffer = new Array()
	    	
	    	dispatcher.addEventListener(eventType,onEventFired, false ,0 ,true)
	    }
	    
	    private function callBuffer():void
	    {
	    	for(var i:int=0; i<buffer.length; i++){
	    		callFunction(buffer[i].name, buffer[i].args)
	    	}
	    	buffer.splice(0)
	    }
	    
	    private function addTobuffer(funcName:String, args:*):void
	    {
	    	buffer.push({name:funcName, args:args})
	    }
	    
	    private function callFunction(name:String, args:*):void
	    {
	    	target[name].apply(null,args)
	    }
	    
	    private function onEventFired(event:Event):void
	    {
	    	eventFired = true
	    	dispatcher.removeEventListener(eventType,onEventFired,false)
	    	dispatcher = null
	    	callBuffer()
	    }
	
	    override flash_proxy function callProperty(methodName:*, ... args:Array):*
	    {
	       if(!eventFired){
	       		addTobuffer(methodName,args)
	       }else{
	       		callFunction(methodName,args)
	       }
	    }
	
	    override flash_proxy function getProperty(name:*):*
	    {
	        return ""
	    }
	
	    override flash_proxy function setProperty(name:*, value:*):void
	    {
	      
	    }
	}
}